package com.zhangmeng.online.exam.utils;

import com.zhangmeng.jwt.dto.LoginUser;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @author zm
 * @date 2025/4/6 16:21
 * @version: 1.0
 */
public class UserUtils {

    public static Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = null;
        if (authentication != null) {
            if (authentication instanceof AnonymousAuthenticationToken) {
                return null;
            }

            if (authentication instanceof UsernamePasswordAuthenticationToken) {
                loginUser = (LoginUser) authentication.getPrincipal();
            }
        }
        if (loginUser != null){
            return loginUser.getId();
        }
        return null;
    }
}
